﻿using AutoMapper;
using D.B.Data.API.Applications.Command.LeaveCommand;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler.LeaveCommandHandler
{
    public class AddLeaveCommandHandler : IRequestHandler<AddLeaveCommand, APIResult<int>>
    {
        private readonly IBaseRepository<WorkflowModel> baseRepository;
        private readonly IBaseRepository<DeptModel> deptRepository;
        private readonly IMapper mapper;

        public AddLeaveCommandHandler(IBaseRepository<WorkflowModel> baseRepository, IMapper mapper, IBaseRepository<DeptModel> userRepository)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
            this.deptRepository = userRepository;
        }

        public Task<APIResult<int>> Handle(AddLeaveCommand request, CancellationToken cancellationToken)
        {
          




            var model = mapper.Map<WorkflowModel>(request);
            //判断添加时候 是否是 部门领导人
            var res = deptRepository.GetAll().Where(s => s.BoosId == request.UserId);
            if (res.Any())
            {
                model.State = true;
                model.IsResult = "同意";
            }


            model.CreateTime = DateTime.Now;
            model.CreateUserId=request.UserId;
            model.LeaveTIme=Convert.ToDateTime(request.LeaveTIme);
            model.ReportTIme=Convert.ToDateTime(request.ReportTIme);
            var count= baseRepository.Add(model);


            APIResult<int> aPIResult = new APIResult<int>();
            aPIResult.Data = count;
            if (count>0)
            {
                aPIResult.Code=EnumCode.Ok;
                aPIResult.Msg = "添加成功";
            }
            else
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Msg = "添加失败";
            }
            return Task.FromResult(aPIResult);






        }
    }
}
